const request = async (url, options = {}) => {
  const token = localStorage.getItem('token')
  
  // 默认配置
  const defaultOptions = {
    headers: {
      'Content-Type': 'application/json',
      // 如果有token就带上
      ...(token ? { Authorization: `Bearer ${token}` } : {})
    }
  }
  
  try {
    const res = await fetch(url, { ...defaultOptions, ...options })
    const data = await res.json()
    
    if (res.status === 401) {
      // token过期,清除登录信息并跳转到登录页
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      window.location.href = '/login'
      return Promise.reject(new Error('登录已过期'))
    }
    
    return data
  } catch (error) {
    return Promise.reject(error)
  }
}

export default request 